package com.idbk.chargestation.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.R;
import com.idbk.chargestation.adapter.CarBrandAdapter;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.base.BaseFragment;
import com.idbk.chargestation.bean.JsonCarBrands;
import com.idbk.chargestation.bean.JsonCarMsgList;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GsonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 汽车品牌选择
 *
 * @author zhx
 */
public class FragmentCarBrands extends BaseFragment {

    private View mView;
    private Context mContext;
    private CarBrandAdapter mAdapter;//汽车品牌适配器
    private ProgressBar mProgressBar;//加载
    public ListView mListView;//车辆品牌显示列表
    private List<JsonCarBrands> mList;
    public JsonCarMsgList result;//搜索结果

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.fragment_car_brands, container, false);

        mContext = getActivity();

        setupView();

        setupData();

        return mView;
    }

    private void setupView() {
        mListView = (ListView) (mView).findViewById(R.id.car_brands_listview);
        mProgressBar = (ProgressBar) (mView).findViewById(R.id.headview_progress);
        mList = new ArrayList<JsonCarBrands>();
        mAdapter = new CarBrandAdapter(mList, mContext);
        mListView.setAdapter(mAdapter);
    }

    private void setupData() {
        ChargeStationAPI.getCarMessage(new EHttpResponse() {

            @Override
            public void onEResponse(String response) {
                result = GsonUtils.toBean(JsonCarMsgList.class, response);
                if (handleResponseStatus(mContext, result)) {
                    for (JsonCarBrands Result : result.vehicleBrands) {
                        mList.add(Result);
                    }
                    mAdapter.notifyDataSetChanged();
                    mProgressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onEErrorResponse(VolleyError error) {
                super.onEErrorResponse(error);
                mProgressBar.setVisibility(View.GONE);
                Toast.makeText(mContext, R.string.common_tip_resultfail,Toast.LENGTH_SHORT).show();
            }
        });
    }

    //返回请求结果
    public JsonCarMsgList getResult() {
        return result;
    }

}
